package com.jackstraw.dbtool.utils;

import com.jackstraw.dbtool.exception.MyException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 所在包：com.jackstraw.e2d.utils
 * 文件名：
 * 版权：稻草人.
 * 项目：e2d
 * 功能描述：
 * 修改人：Xinglz
 * 修改时间：2020-01-15 16:14
 */
public class ExcelUtil {

    private static MultipartFile excel;

    private static Workbook workbook;

    public static void initExcel(MultipartFile file) {
        excel = file;
        workbook = getWorkBook(file);
    }

    public static MultipartFile getExcel() {
        if (excel == null)
            throw new MyException("Excel尚未加载，请重试!");
        return excel;
    }

    public static Workbook getWorkbook() {
        return workbook;
    }

    public static void cleanExcel() {
        excel = null;
        workbook = null;
    }

    /**
     * 根据上传文件获取可操作excel对象
     * @param file
     * @return
     */
    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
            if (fileName.endsWith("xls")) {
                //2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith("xlsx")) {
                //2007 及2007以上
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            e.getMessage();
        }
        return workbook;
    }
}
